package com.wuyou.mybatishandlerdemo.advice;

import com.wuyou.mybatishandlerdemo.component.EmailComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * GlobalAdviceController
 *
 * @Date 2025-09-26 10:35
 * @Author 无忧
 */
@RestControllerAdvice
@Slf4j
public class GlobalAdviceController {

    @Autowired
    private EmailComponent emailComponent;

    /**
     * 拦截所有异常
     */
    @ExceptionHandler(Throwable.class)
    public Object handleThrowable(Throwable throwable) {
        log.error("全局异常", throwable);
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("msg", throwable.getMessage());
        map.put("detailMsg", asString(throwable));

        emailComponent.sendSimpleEmail("wuyou96111@163.com", "ZMH系统报错",
                throwable.getMessage() +
                        "发送时间: " + new java.util.Date());
        return map;
    }
    public static String asString(Throwable ex){
        if(ex != null){
            return ex.getMessage() +"\r\n"+ Arrays.toString(ex.getStackTrace());
        }
        return "";
    }
}
